package com.klb.action.catalog;

import com.klb.model.BbsArticle;
import com.klb.service.catalog.impl.ArticleServiceCatalogImpl;
import com.klb.service.catalog.impl.BlockServiceCatalogImpl;
import com.klb.tools.PostValue;
import com.klb.tools.Sessions;
import com.klb.tools.Tools;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by fujia on 2016/6/5.
 */
public class ArticleActionCatalog extends ActionSupport {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

    private HashMap<String,Object> data;
    
    private ArticleServiceCatalogImpl articleServiceCatalog;
    private BlockServiceCatalogImpl blockServiceCatalog;


	public void setArticleServiceCatalog(ArticleServiceCatalogImpl articleServiceCatalog) {
		this.articleServiceCatalog = articleServiceCatalog;
	}

	public void setBlockServiceCatalog(BlockServiceCatalogImpl blockServiceCatalog) {
		this.blockServiceCatalog = blockServiceCatalog;
	}

	@Override
    public String execute() throws Exception {
        HttpServletRequest request = ServletActionContext.getRequest();

        if (!Tools.objectIsNullOrNot(request.getParameter("block"))){
            int blockId = Integer.parseInt(request.getParameter("block"));
            List<BbsArticle> list = this.articleServiceCatalog.getAllBlockArticles(blockId);
            String title = this.blockServiceCatalog.getTitleById(blockId);

            Sessions.setSession("articles", list);
            Sessions.setSession("blockName", title);

            return SUCCESS;
        }

        return ERROR;
    }

    public String jsonForArticle(){
        JSONObject jsonObject = PostValue.getJsonObject();

        if (!Tools.objectIsNullOrNot(jsonObject)){
            int blockId = (int) jsonObject.get("blockId");

            List<BbsArticle> list = this.articleServiceCatalog.getAllBlockArticles(blockId);
            String title = this.blockServiceCatalog.getTitleById(blockId);

            this.data = new HashMap<>();

            this.data.put("articles", list);
            this.data.put("blockName", title);
            this.data.put("success", true);

        } else {
            this.data = null;
        }

        return SUCCESS;

    }

    public Map<String, Object> getData() {
        return data;
    }

}
